const mongoose = require("mongoose");
const Article = require("../models/articleModel");

//增加文章
exports.createArticle = async (req, res) => {
  try {
    const newArticle = await Article.create(req.body);
    // 201 Created 已创建
    res.status(201).json({
      status: "success",
      data: newArticle,
    });
  } catch (err) {
    console.log("添加文章失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//删除文章
exports.deleteArticle = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const data = await Article.deleteOne({ _id: id });
    res.status(200).json({
      status: "success",
      data: data,
    });
  } catch (err) {
    console.log("删除文章失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//修改文章
exports.updateArticle = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.params);
    const newArticle = await Article.findByIdAndUpdate(id, req.body, {
      new: true,
    });
    if (!newArticle) {
      return res.status(404).json({
        message: "修改的文章并不存在",
      });
    }
    res.status(200).json({
      status: "success",
      data: newArticle,
    });
  } catch (err) {
    console.log("修改文章失败", err);
    res.status(404).json({
      err,
    });
  }
};

//获取所有文章
exports.getAllArticle = async (req, res) => {
  try {
    const articleList = await Article.find();
    res.status(200).json({
      status: "success",
      data: articleList,
    });
  } catch (err) {
    console.log("获取所有文章失败", err);
    res.status(404).json({
      Error: err,
    });
  }
};

//发布文章  0普通文章  1总体要求 2组织架构 3工作方案
exports.publishArticle = async (req, res) => {
  try {
    const id = mongoose.Types.ObjectId(req.body._id);
    const type = req.body.type;

    // 1 2 3只能发一篇 因此需要重置
    await Article.updateMany({ type: type }, { $set: { type: 0 } });

    await Article.updateOne({ _id: id }, { $set: { type: type } });

    const newArticleList = await Article.find();
    // if (!newArticle) {
    //   return res.status(404).json({
    //     message: "修改的文章并不存在",
    //   });
    // }
    res.status(200).json({
      status: "success",
      data: newArticleList,
    });
  } catch (err) {
    console.log("文章发布失败", err);
    res.status(404).json({
      err,
    });
  }
};
